package com.nuanshui.framework.middleware.mq;


import java.util.Date;

import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;


public class MessageSend  implements InitializingBean{
	
    @Autowired
	private AmqpTemplate amqpTemplate;
	
	 @Value("${mq.message.suffix}")
	 private String suffix=""; 
	 
	 public MessageSend() {
		System.out.println(suffix);
	}
	/**
	 * 发送消息
	 * @param 
	 * @author guohao
	 * @date 2016年3月1日 下午2:42:53
	 */
	public void send(MQMessage mqMessage) {
		
		if(!mqMessage.isDeadQueue()) {
			amqpTemplate.convertAndSend(mqMessage.getType().getExchange()+suffix,mqMessage.getType().getQueue()+suffix,mqMessage.body);		
		}else {
			amqpTemplate.convertAndSend("exchange.dead",mqMessage.getType().getQueue()+suffix,mqMessage.body);		

		}
	}
	
	/**
	 * 发送动态延迟消息
	 * @param 
	 * @author guohao
	 * @date 2016年5月27日 下午3:29:40
	 * @since $
	 */
	public void  sendDynamicDelay(MQMessage mqMessage) {
		Date consumeTime = mqMessage.getConsumeTime();
		if(consumeTime == null) consumeTime = new Date();
		long subsistTime =  consumeTime.getTime()-System.currentTimeMillis();		
		MessageProperties messageProperties = new MessageProperties();	
		messageProperties.setExpiration(subsistTime+"");
		messageProperties.setPriority(0);
		new Message(mqMessage.getBody().getBytes(),messageProperties);
	}
	@Override
	public void afterPropertiesSet() throws Exception {
		System.out.println(suffix);
		
	}

}
